import { DEFAULT_PROTABLE_OPTIONS } from '@/constants';
import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  PlusCircleOutlined,
} from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Popconfirm, Tag, Tooltip } from 'antd';
import { useMemo, useRef, useState } from 'react';
import dayjs from 'dayjs';

import { getUserListPaginated, removeUser } from '@/services/userManageApi';
import UserEditDrawer from './components/EditDrawer';

/**
 * 用户管理
 */
export default function UserManagePage() {
  const [openEditDrawer, setOpenEditDrawer] = useState(false);
  const [editRecord, setEditRecord] = useState<USER.UserModel | null>(null);
  const tableActionRef = useRef<ActionType>();
  const requestRemove = useRequest(removeUser, {
    manual: true, // 关闭自动请求
    onSuccess: () => {
      // 重新加载表格
      tableActionRef.current?.reload();
    },
  });

  const columns = useMemo<ProColumns<USER.UserModel>[]>(
    () => [
      {
        dataIndex: 'avatar',
        title: '头像',
        hideInSearch: true,
        render: (_, record) => {
          // 构建完整的图片访问地址
          const avatarUrl = record.avatar ? `http://www.gameback.cn/${record.avatar}~tplv-trmyndwfss-image.image` : null;
          return avatarUrl ? (
            <img 
              src={avatarUrl} 
              alt="头像" 
              style={{ width: '40px', height: '40px', borderRadius: '50%' }} 
            />
          ) : null;
        },
      },
      {
        dataIndex: 'name',
        title: '姓名',
      },
      {
        dataIndex: 'nickName',
        title: '昵称',
        hideInSearch: true,
      },
      {
        dataIndex: 'className',
        title: '班级',
        hideInSearch: true,
      },
      {
        dataIndex: 'stuNo',
        title: '学号',
        hideInSearch: true,
      },
      {
        dataIndex: 'phone',
        title: '手机号',
        hideInSearch: true,
      },
      {
        dataIndex: 'email',
        title: '邮箱',
        hideInSearch: true,
      },
      {
        dataIndex: 'role',
        title: '角色',
        renderText: (val) => {
          if (val === 'ADMIN') return <Tag color="red">管理员</Tag>;
          if (val === 'TEACHER') return <Tag color="blue">教师</Tag>;
          if (val === 'STUDENT') return <Tag color="green">学生</Tag>;
          if (val === 'MANAGER') return <Tag color="purple">小管家</Tag>;
          return <Tag color="default">{val}</Tag>;
        },
        valueEnum: {
          ADMIN: { text: '管理员' },
          TEACHER: { text: '教师' },
          STUDENT: { text: '学生' },
          MANAGER: { text: '小管家' },
        },
      },
      {
        dataIndex: 'gender',
        title: '性别',
        hideInSearch: true,
        valueEnum: {
          1: { text: '男' },
          0: { text: '女' },
        },
      },
      {
        dataIndex: 'createTime',
        title: '创建时间',
        hideInSearch: true,
        render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-',
      },
      {
        dataIndex: 'createTime',
        title: '创建时间',
        hideInTable: true,
        valueType: 'dateRange',
        search: {
          transform: (value) => {
            return {
              startDate: value[0] ? dayjs(value[0]).format('YYYY-MM-DD') : undefined,
              endDate: value[1] ? dayjs(value[1]).format('YYYY-MM-DD') : undefined,
            };
          },
        },
      },
      {
        dataIndex: 'status',
        title: '状态',
        valueEnum: {
          '1': { text: '在校', status: 'Success' },
          '2': { text: '毕业', status: 'Default' },
          '3': { text: '休学', status: 'Warning' },
          '4': { text: '封禁', status: 'Error' },
        },
      },
      {
        title: '操作',
        valueType: 'option',
        width: 90,
        fixed: 'right',
        render: (_, row) => [
          <Tooltip key="edit" title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => {
                setEditRecord(row);
                setOpenEditDrawer(true);
              }}
            ></Button>
          </Tooltip>,
          <Popconfirm
            key="delete"
            okType="danger"
            title="删除当前用户"
            onConfirm={() => requestRemove.run(row.id)}
            okButtonProps={{
              loading: requestRemove.loading,
            }}
          >
            <Button type="text" danger icon={<DeleteOutlined />}></Button>
          </Popconfirm>,
        ],
      },
    ],
    [requestRemove.loading],
  );

  return (
    <PageContainer title="用户管理">
      <ProTable<USER.UserModel>
        {...DEFAULT_PROTABLE_OPTIONS}
        actionRef={tableActionRef}
        columns={columns}
        request={async (params) => {
          // 转换参数格式
          const { current, pageSize, ...rest } = params;
          const result = await getUserListPaginated({
            current,
            pageSize,
            ...rest,
            status: params.status,
          });
          
          // 适配新的后端接口响应格式
          if (result.code === 200 && result.data) {
            return {
              data: result.data.records || [],
              success: true,
              total: result.data.total || 0,
              current: result.data.current,
              pageSize: result.data.pageSize,
            };
          }
          return {
            data: [],
            success: false,
            total: 0,
          };
        }}
        scroll={{ x: 'max-content' }}
        toolbar={{
          title: '用户列表',
          actions: [
            <Button
              key="add"
              type="primary"
              icon={<PlusCircleOutlined />}
              onClick={() => setOpenEditDrawer(true)}
            >
              新增
            </Button>,
            <Button key="export" type="dashed" icon={<DownloadOutlined />}>
              导出
            </Button>,
          ],
        }}
      ></ProTable>
      <UserEditDrawer
        open={openEditDrawer}
        data={editRecord}
        onFinish={() => {
          setOpenEditDrawer(false);
          setEditRecord(null);
          // 刷新表格
          tableActionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
}